package org.ljdp.bootstrap.startup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.ljdp.common.config.Env;
import org.ljdp.common.spring.SpringContextManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LjdpStartup {
	private static final Logger logger = LoggerFactory.getLogger(LjdpStartup.class);
	
	private String shutdownThread;
	
	public void run(String appname) {
		logger.info("【"+appname+"】开始启动");
		Env.buildCurrentEnv();
		SpringContextManager.registerShutdownHook();
		
		if(shutdownThread != null) {
			try {
				Class shutdownCls = Class.forName(shutdownThread);
				Thread shutdownThread = (Thread)shutdownCls.newInstance();
				Runtime.getRuntime().addShutdownHook(shutdownThread);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		Runtime.getRuntime().addShutdownHook(new Shutdown(appname));
		
		logger.info("【"+appname+"】应用启动完成");
		System.out.println("--------------------[命令说明]-----------------------------");
		System.out.println("shutdown：关闭应用");
		System.out.println("-----------------------------------------------------------");
		BufferedReader cmd = new BufferedReader(new InputStreamReader(System.in));
		try {
			String cmdKey;
			while (!(cmdKey = cmd.readLine()).equalsIgnoreCase("shutdown")) {
				System.out.println("your input : " + cmdKey);
			}
		} catch (IOException e) {
			logger.error("System Startup Error : "+e.getMessage(), e);
		} finally {
			System.exit(0);
		}
	}

	public String getShutdownThread() {
		return shutdownThread;
	}

	public void setShutdownThread(String shutdownThread) {
		this.shutdownThread = shutdownThread;
	}
}
